package cn.edu.ldu.communityqa.communityqa.interceptor;

import cn.edu.ldu.communityqa.communityqa.service.SessionService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class ApiLoginInterceptor implements HandlerInterceptor {

    public static final String SESSION_COOKIE_USERNAME = "username";
    public static final String SESSION_COOKIE_PASSWORD = "password";
    private static final String LOGIN_REQUIRED_JSON = "{\"msg\": \"请先登录\"}";
    private final SessionService sessionService;

    @Autowired
    public ApiLoginInterceptor(SessionService sessionService) {
        this.sessionService = sessionService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查请求路径是否以 /api 开头
        if (request.getRequestURI().startsWith("/api")) {
            // 获取名为 JSESSIONID 的 Cookie
            String name = null;
            String password = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (SESSION_COOKIE_USERNAME.equals(cookie.getName())) {
                        name = cookie.getValue();
                    }
                    if (SESSION_COOKIE_PASSWORD.equals(cookie.getName())) {
                        password = cookie.getValue();
                    }
                }
            }

            // 验证 session ID 是否有效（这里假设有一个服务来验证）
            if (name == null || password == null || !sessionService.isValidSession(name, password)) {
                // 如果没有找到有效的 session ID，则返回 JSON 响应
                sendJsonResponse(response, LOGIN_REQUIRED_JSON);
                return false;
            }
        }

        // 如果不是 /api 请求，或者 session ID 有效，则允许请求继续
        return true;
    }

    private void sendJsonResponse(HttpServletResponse response, String json) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
        response.getWriter().flush();
    }
}